package com.hljx.filter;

import com.alibaba.fastjson.JSONArray;
import com.hljx.config.Result;
import com.hljx.config.exception.DataEnums;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author qtx
 * @since 2022/11/2
 */
@Component
public class CommonMethod {

    private final ThreadLocal<String> userCode = new ThreadLocal<>();

    private final ThreadLocal<String> userName = new ThreadLocal<>();


    public String getUser() {
        return userCode.get();
    }

    public String getUserName() {
        return userName.get();
    }

    public void setUserCode(String userCode) {
        this.userCode.set(userCode);
    }

    public void setUserName(String userName) {
        this.userName.set(userName);
    }

    /**
     * 过滤器返回信息
     *
     * @param response  response
     * @param dataEnums 错误信息
     * @throws IOException io失败
     */
    public void failed(HttpServletResponse response, DataEnums dataEnums) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        //设置响应状态码
        response.setStatus(HttpServletResponse.SC_OK);
        //输入响应内容
        PrintWriter writer = response.getWriter();
        String s = JSONArray.toJSON(Result.failed(dataEnums)).toString();
        writer.write(s);
        writer.flush();
    }

    public void clear(){
        userCode.remove();
        userName.remove();
    }
}
